package com.haotunet.app.goldtreasure.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.service.LocationService;
import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.activity.DynamicDetailActivity;
import com.haotunet.app.goldtreasure.activity.MyApplication;
import com.haotunet.app.goldtreasure.activity.NearGoldShopActivity;
import com.haotunet.app.goldtreasure.adapter.MerchantAdapter;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.MsgInfo;
import com.haotunet.app.goldtreasure.model.StoreInfo;
import com.haotunet.app.goldtreasure.model.StoreModel;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.net.UrlUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.LocationUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.TitleView;
import com.haotunet.app.pulltorefresh.PullToRefreshLayout;
import com.haotunet.app.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.haotunet.app.pulltorefresh.pullableView.PullableListView;

import java.util.ArrayList;
import java.util.List;

public class MerchantServiceFragment extends BaseFragment implements OnClickListener {
    private LocationService locationService;
    private TitleView mTitleView;
    private PullableListView mLvMerchant;
    private TextView noSearchResultView;
    private TextView tvCurrentLocat;
    private EditText etSearch;
    private ImageView ivDelete;
    private ImageView ivRefresh, ivLocate;
    private View vMask;
    private PullToRefreshLayout mfreshLayout;
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;
    private ShareStore shareStore;
    private View view;
    private int pageNum = 20;
    private double longitude;
    private double latitude;
    private final int GET_STORE_LIST_SUCCESS = 2;
    private final int LOAD_MORE_STORE_LIST_SUCCESS = 3;
    private boolean keyboardShown = false;
    private MerchantAdapter merchantAdapter;
    private List<StoreInfo> mOriginalShopList = new ArrayList<>();
    private boolean isSaveOriginalData = false;
    private String mSearchText = "";
    private Handler handle = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case GET_STORE_LIST_SUCCESS:
                    StoreModel storeModel = (StoreModel) msg.obj;
                    if (storeModel.getShopList().size() == 0) {
                        noSearchResultView.setVisibility(View.VISIBLE);
                    } else {
                        noSearchResultView.setVisibility(View.GONE);
                        if (!isSaveOriginalData) {
                            mOriginalShopList = storeModel.getShopList();
                            isSaveOriginalData = true;
                        }
                    }
                    merchantAdapter.setDatas(storeModel.getShopList());
                    break;
                case LOAD_MORE_STORE_LIST_SUCCESS:
                    StoreModel moreModel = (StoreModel) msg.obj;
                    if (moreModel.getShopList().size() == 0) {
                        UIHelper.showToast(getActivity(), getString(R.string.last_page_hint));
                    }
                    merchantAdapter.addDatas(moreModel.getShopList());
                    break;
                default:
                    break;
            }
        }

    };

    public static MerchantServiceFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString("type", type);
        MerchantServiceFragment fragment = new MerchantServiceFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_merchant_service, container, false);
        shareStore = new ShareStore(getActivity());
        isPrepared = true;
        initView();
        if ("exchangeSuccess".equals(getArguments().getString("type"))) {
            getStoreList(0, "", "");
        }
        return view;
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        locationService.unregisterListener(mListener); // 注销掉监听
        locationService.stop(); // 停止定位服务
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
        // -----------location config ------------
        if (isActivityAvailable()) {
            locationService = ((MyApplication) getActivity().getApplication()).locationService;
            // 获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
            locationService.registerListener(mListener);
            // 注册监听
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
            locationService.start();
        }
    }

    private void initView() {
        mTitleView = (TitleView) view.findViewById(R.id.title_view_near);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getTitletextView().setText(getString(R.string.main_menu2_txt));
        mTitleView.getGuideView().setVisibility(View.VISIBLE);
        mTitleView.getGuideView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityUtils.gotoNewGuideLines(getActivity());
            }
        });
        mTitleView.getNotificationView().setVisibility(View.VISIBLE);
        mTitleView.getNotificationView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), DynamicDetailActivity.class);
                intent.putExtra("activityUrl", UrlUtil.MESSAGE_CENTER);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 6);
            }
        });
        noSearchResultView = (TextView) view.findViewById(R.id.no_search_result_view);
        mfreshLayout = (PullToRefreshLayout) view.findViewById(R.id.id_swipe_ly);
        etSearch = (EditText) view.findViewById(R.id.et_search_shop);
        etSearch.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    hideKeybaord();
                    mSearchText = etSearch.getText().toString();
                    if (!TextUtils.isEmpty(mSearchText)) {
                        getStoreList(0, mSearchText.trim(), "");
                    }
                    return true;
                }
                return false;
            }
        });

        ivLocate = (ImageView) view.findViewById(R.id.iv_locate);
        ivLocate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NearGoldShopActivity.class);
                startActivity(intent);
            }
        });
        tvCurrentLocat = (TextView) view.findViewById(R.id.txt_current_location);
        ivDelete = (ImageView) view.findViewById(R.id.iv_delete);
        ivRefresh = (ImageView) view.findViewById(R.id.iv_refresh);
        mLvMerchant = (PullableListView) view.findViewById(R.id.lv_merchant);
        merchantAdapter = new MerchantAdapter(getActivity(), null);
        mLvMerchant.setAdapter(merchantAdapter);
        ivRefresh.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        vMask = view.findViewById(R.id.v_mask);
        vMask.setOnClickListener(this);
        initEditext();
        RefreshData(0);
    }

    private void initEditext() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    ivDelete.setVisibility(View.VISIBLE);
                } else {
                    ivDelete.setVisibility(View.GONE);
                    mSearchText = "";
                    merchantAdapter.setDatas(mOriginalShopList);
                    noSearchResultView.setVisibility(View.GONE);
                }
            }
        });

        etSearch.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                setKeyboardShown(keyboardShown());
            }
        });
    }


    private boolean keyboardShown() {
        final int softKeyboardHeight = 100;
        View rootView = etSearch.getRootView();
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }

    private void RefreshData(final int pagenum) {
        mfreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
                getStoreList(pagenum, mSearchText, "refresh");
                pageNum = 20;
            }

            @Override
            public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
                getStoreList(pageNum, mSearchText, "loadmore");
            }
        });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            requestUnreadMsg();
            return;
        }
        getStoreList(0, "", "");
        requestUnreadMsg();
    }

    private void requestUnreadMsg() {
        if (shareStore.getBoolean(Strs.IS_LOGIN, false)) {
            getUnReadMsg();
        }
    }

    private void getStoreList(int pagenum, String address, final String action) {
        double[] bd09_To_Gcj02 = LocationUtils.Bd09_To_gcj02(latitude, longitude);
        ActionUtil actionUtil = new ActionUtil(getActivity());
        actionUtil.getStoreList(pagenum, bd09_To_Gcj02[1], bd09_To_Gcj02[0], address, 1);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (!isActivityAvailable()) {
                    return;
                }
                StoreModel storeModel = (StoreModel) model;
                if (storeModel == null) {
                    UIHelper.showToast(getActivity(), getString(R.string.rank_fail));
                    mfreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                    return;
                }
                if (storeModel.getErrorMsg() != null) {
                    UIHelper.showToast(getActivity(), storeModel.getErrorMsg());

                } else {
                    mHasLoadedOnce = true;
                    if (action.equals("refresh") || action.equals("loadmore")) {
                        mfreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                    Message msg = new Message();
                    if (action.equals("loadmore")) {
                        msg.what = LOAD_MORE_STORE_LIST_SUCCESS;
                        pageNum = pageNum + 20;
                    } else {
                        msg.what = GET_STORE_LIST_SUCCESS;
                    }
                    msg.obj = storeModel;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    public void logMsg(String str) {
        try {
            locationService.stop();
            tvCurrentLocat.setText(getString(R.string.current_location) + str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                longitude = location.getLongitude();
                latitude = location.getLatitude();

                if (!TextUtils.isEmpty(location.getCity()) && !TextUtils.isEmpty(location.getDistrict())
                        && !TextUtils.isEmpty(location.getStreet())) {
                    logMsg(location.getCity() + location.getDistrict() + location.getStreet());
                } else {
                    tvCurrentLocat.setText(getString(R.string.current_location) + getString(R.string.empty));
                }
            }
        }

    };

    private void getUnReadMsg() {
        ActionUtil actionUtil = new ActionUtil(getActivity());
        actionUtil.getUnReadMsg();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                MsgInfo msgInfo = (MsgInfo) model;
                if (msgInfo == null) {
                    return;
                }
                int unreadMsgCount = msgInfo.getUnreadMsgCount();
                if (unreadMsgCount != 0) {
                    mTitleView.getNotificationView().setSelected(true);
                } else {
                    mTitleView.getNotificationView().setSelected(false);
                }
            }
        });
    }

    @SuppressWarnings("static-access")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6 && resultCode == getActivity().RESULT_OK) {
            requestUnreadMsg();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_refresh:
                locationService.start();
                Animation loadAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_anim);
                ivRefresh.startAnimation(loadAnimation);
                break;
            case R.id.iv_delete:
                etSearch.setText("");
                showKeyBoard();
                break;
            case R.id.v_mask:
                hideKeybaord();
                break;
        }
    }

    private void hideKeybaord() {
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void showKeyBoard() {
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, 0);
        }
    }

    public void setKeyboardShown(boolean keyboardShown) {
        boolean oldValue = this.keyboardShown;
        this.keyboardShown = keyboardShown;
        if (oldValue != this.keyboardShown) {
            this.vMask.setVisibility(this.keyboardShown ? View.VISIBLE : View.INVISIBLE);
            etSearch.setCursorVisible(this.keyboardShown);
        }
    }

}
